<?php
namespace App\Services;
use Exception,Log;

class ApisafeService
{
    public static function checkApiSafe($key,$sign,$timestamp,$token,$appid)
    {
        if (empty($key) || empty($sign) || empty($timestamp)) return ["status"=>"error","msg"=>"签名错误,请稍后尝试!"];
        if ((time()-$timestamp) >= 300) return ["status"=>"error","msg"=>"签名已过期,请刷新页面重新访问!"];
        $iv = $timestamp."WLWLWL";
        if (empty($token) || empty($appid)) {
            $md5sign = md5("wl".$iv.$key.$iv."lw");
            if ($sign != $md5sign) return ["status"=>"error","msg"=>"签名错误,请稍后尝试!"];
        } else {
            $md5sign = md5($appid.$iv.$key.$iv."lw");
            if ($token != $md5sign) return ["status"=>"error","msg"=>"签名错误,请稍后尝试!"];
        }
        return ["status"=>"success","msg"=>"签名正确!"];
    }

    public static function apiAesEncrypt($key,$iv,$data)
    {
        $iv = $iv."WLWLWL";
        $encrypted = base64_encode(openssl_encrypt(json_encode($data),"AES-128-CBC",$key,OPENSSL_RAW_DATA,$iv));
        return $encrypted;
    }

    public static function apiAesDecrypt($key,$iv,$data)
    {
        $iv = $iv."WLWLWL";
        $decrypted = openssl_decrypt(base64_decode($data), 'AES-128-CBC', $key,OPENSSL_RAW_DATA,$iv);
        return json_decode($decrypted);
    }

    public static function aesEncryptDefault($data)
    {
        $key = 'Mn2sd56Msd789888';
        $iv = 'S221456Msd789888';
        $encrypted = base64_encode(openssl_encrypt($data,"AES-128-CBC",$key,OPENSSL_RAW_DATA,$iv));
        return $encrypted;
    }

    public static function aesDncryptDefault($data)
    {
        $key = 'Mn2sd56Msd789888';
        $iv = 'S221456Msd789888';
        $decrypted = openssl_decrypt(base64_decode($data), 'AES-128-CBC', $key,OPENSSL_RAW_DATA,$iv);
        return $decrypted;
    }
}
